<script setup lang="ts">
import { reactive,ref, computed, watchEffect, onMounted, watch, onBeforeUnmount } from 'vue'
import { useRouter, useRoute } from 'vue-router';
// import axios from 'axios'
// import JSZip from 'jszip';
import type { UnwrapRef } from 'vue';
import { setCookie } from '../utils/auth'
// import { useUserStore } from '../store/modules/user'
import { userSiteArticleList, userSiteArticleDetails, userSiteArticleZipImage, getuserinfo,articlePublish, userSiteArticleSetRelease, pictureUploadproxy, articleLists, articleRemove,articleWithdraw, adnewspvtrend, adnewsincomeoverview, getSquareMissionList, articlePublishNum } from "../api/article"
import UploadPhoto from "./UploadPhoto.vue"
import { Modal } from 'ant-design-vue';
import { message } from 'ant-design-vue';
import { createVNode } from 'vue';
import { storage } from '../utils/storage'
import Cookies from 'js-cookie'
import { download_file } from '../utils/ipcRequest'

type Key = string | number;

const props:any = defineProps({
    activeKey: String
})

const columns = [
  // {
  //   name: 'Name',
  //   title: '关联账号',
  //   dataIndex: 'name',
  //   key: 'name',
  // },
  {
    title: '标题',
    dataIndex: 'title',
    key: 'title',
    ellipsis: true,
  },
  {
    title: '来源',
    dataIndex: 'source_url',
    key: 'source_url',
    ellipsis: true,
  },
  {
    title: '文章状态',
    key: 'status',
    dataIndex: 'status',
  },
  {
    title: '时间',
    key: 'create_time',
  },
  {
    title: '操作状态',
    key: 'isDownload',
    dataIndex: 'isDownload',
    width: 240,
  },
  // {
  //   title: '操作',
  //   key: 'action'
  // }
];

const articleList:any = ref([]);

const router:any = useRouter()
const route:any = useRoute()
// const userStore = useUserStore()
// console.log('router',router,router.currentRoute.value.fullpath, toRaw(router).currentRoute.value.fullPath,  route.query.siteId, route.query.cookie);

const open = ref<boolean>(false);
const title = ref<string>('一键发布')
const progressBar = ref<string>('')
const state = reactive<{
  selectedRowKeys: Key[];
  selectedRows: Key[];
  loading: boolean;
}>({
  selectedRowKeys: [], // Check here to configure the default column
  selectedRows: [],
  loading: false,
});
const pagination = computed(() => ({
  total: total.value,
  current: current.value,
  pageSize: pageSize.value,
  showSizeChanger: false, // 取消每页条数选择器
}));
const hasSelected = computed(() => state.selectedRowKeys.length > 0);

const selectData:any = ref([]) // 多选的数据
// 一键发布
const start = async () => {
  state.loading = true;
  title.value = '一键发布'
  count.value = 0
  selectData.value = []
  // let unzipArr = JSON.parse(sessionStorage.get('unzip-data' + current.value))
  // let resultData: any = ''
  // if(unzipArr) {
  //    resultData = unzipArr.filter((item1:any) =>
  //     state.selectedRowKeys.some(item2 => item2 === item1.value.article_id)
  //   );
  // }

  // //去重
  // const uniqueArray = resultData.filter((item:any, index:any, self:any) =>
  //   index === self.findIndex((t:any) => t.value.article_id === item.value.article_id)
  // );
  // //获取未解压的数组
  // let resultData2:any = ''
  // if(unzipArr) {
  //   resultData2 = state.selectedRows.filter((item2:any) =>
  //     !unzipArr.some((item1:any) => item2.article_id === item1.value.article_id)
  //   );
  // }
  // console.log('unzipArr', unzipArr, resultData,uniqueArray, resultData2)
  // 获取id数组
    let resultData = state.selectedRowKeys.filter((item2:any) =>
       articleList.value.some(item1 => item2 === item1.article_id && item1.isDownload)
    );
    // 获取对象数组
    let resultData2 = state.selectedRows.filter((item2:any) =>
       articleList.value.some(item1 => item2.article_id === item1.article_id && item1.isDownload)
    );
        // 获取未解压数组
    let resultData3 = state.selectedRows.filter((item2:any) =>
       articleList.value.some(item1 => item2.article_id === item1.article_id && !item1.isDownload)
    );
    console.log(resultData, resultData2)
  if(resultData2.length > 0) {
    for (let i in resultData2) {
      selectData.value.push({
        info: {},
        articleId: resultData2[i]['article_id'],
        fileLists: [],
        modalOpen: false,
        vertical_cover: resultData2[i]['vertical_cover'],
        activity_list: activity_list.value,
        square_mission_List: mission_list.value,
      })
      const filePathJson = `images_${resultData2[i]['article_id']}.json`;
      const result = await window.electron.ipcRenderer.invoke('json-directory', filePathJson);
      console.log(result)
      if (result.type == 2) {
        let jsonData =  JSON.parse(result.urlArr)
        console.log(jsonData)
        if(jsonData.data.length == 0) {
          window.electron.ipcRenderer.invoke('delete-file', filePathJson).then(res => {
            console.log(res)
            if(res.success) {
              console.log('文件删除成功')
            } else {
              console.log('删除文件失败',res.message)
            }
          })
          imgNum.value = jsonData.data.length
          // message.warning('文件为空，请刷新重新上传');
          resultData2[i]['isPublish'] = false
          resultData2[i]['publishReason'] = '文件为空,请刷新'
          resultData2[i]['errorColor3'] = 'error'
          resultData2[i]['publishText'] = '发布失败'
          state.loading = false;
          title.value = '一键发布'
          selectData.value = []
          state.selectedRowKeys = [];
          state.selectedRows = []
        } else {
          selectData.value?.forEach((item: any, index:any) => {
            if (resultData2[i]['article_id'] === item.articleId) {
              selectData.value[index]['fileLists'] = jsonData.data; // 替换为空的内容部分--给数组赋值
              selectData.value[index]['modalOpen'] = true
              count.value++
            }
          });
          onArticleDetails(resultData2[i]['article_id']) // 获取详情内容
        }
      }else if(result.type == 1) {
        // message.error({
        //   content: () => `未读取到文件：${filePathJson}`,
        //   duration: 2
        // });
        resultData2[i]['isPublish'] = false
        resultData2[i]['publishReason'] = '未读取到文件'
        resultData2[i]['errorColor3'] = 'error'
        resultData2[i]['publishText'] = '发布失败'
        state.loading = false;
        title.value = '一键发布'
        selectData.value = []
        state.selectedRowKeys = [];
        state.selectedRows = []
      } else {
        console.log(`读取文件失败：${result.message}`);
        // message.error({
        //   content: () => `读取 ${filePathJson} 文件失败`,
        //   duration: 2
        // });
        resultData2[i]['isPublish'] = false
        resultData2[i]['publishReason'] = `读取${filePathJson}文件失败`
        resultData2[i]['errorColor3'] = 'error'
        resultData2[i]['publishText'] = '发布失败'
        state.loading = false;
        title.value = '一键发布'
        selectData.value = []
        state.selectedRowKeys = [];
        state.selectedRows = []
      }
      // const resArr = await window.electron.ipcRenderer.invoke('read-file', `images_${resultData[i]}`)
      // console.log(resArr); // 输出下载成功信息
      // if(Array.isArray(resArr)) {
      //   onArticleDetails(resultData[i]) // 获取详情内容
      //   uploadPhotos(resArr, resultData[i]) // 上传图片
      // }
    }
  }else {
    for (let i in resultData3) {
      resultData3[i]['isDownload'] = false
      resultData3[i]['downloadReason'] = `未解压`
      resultData3[i]['errorColor2'] = 'error'
    }
    // message.warning('当前文章未解压');
    state.loading = false;
    title.value = '一键发布'
    selectData.value = []
    state.selectedRowKeys = [];
    state.selectedRows = []
  }
};

// 确定发布
const handleOk = async (resolve, reject,idx:any) => {
  // 同步执行
  const executeNextOk = (index) => {
      // 判断循环执行完了后执行
      if(index >= selectData.value.length) {
        console.log('sdsdsdsdsddsd')
        fileLists.value = []
        state.loading = false;
        state.selectedRowKeys = [];
        state.selectedRows = []
        title.value = '一键发布'
        selectData.value = []
        resolve()
        onArticleList()
        onDeleteList()
        return
      }
    const currentItem = selectData.value[index];
    let html_content:any = '' // html内容
      const resultData = currentItem.fileLists?.reduce((acc:any, item1:any) => {
        let matchingItem:any = ''
        if(!Array.isArray(currentItem.info['images'])) {
          matchingItem = JSON.parse(currentItem.info['images']).find((item2:any) => item2.url.slice(item2.url.lastIndexOf('/') + 1) === item1.value.name);
        } else {
          matchingItem = currentItem.info['images'].find((item2:any) => item2.url.slice(item2.url.lastIndexOf('/') + 1) === item1.value.name);
        }
        if (matchingItem) {
          acc.push({  ...matchingItem,...item1.value }); // 将合并后的对象添加到结果数组中
        }
        return acc;
      }, []); // 初始值为空数组
      // html内容
      if(resultData.length > 0) {
        resultData.forEach((element:any, index:any) => {
          if(index == 0) {
            html_content = currentItem.info.html_content.replace(element.key, `<img src="${element.https_url}" alt="">`);
          } else {
            html_content = html_content.replace(element.key, `<img src="${element.https_url}" alt="">`);
          }
        });
      } else {
        html_content = currentItem.info.html_content
      }
      if(currentItem.info['min_title'] && !Array.isArray(currentItem.info['min_title']))  {
        JSON.parse(currentItem.info['min_title']).forEach((element:any) => {
          html_content = html_content.replace(element.label,element.html);
        });
      }else  {
        currentItem.info['min_title'].forEach((element:any) => {
          html_content = html_content.replace(element.label,element.html);
        })
      }
      let cover_image = currentItem.fileLists?.find((items:any) => currentItem.info.cover.slice(currentItem.info.cover.lastIndexOf('/') + 1) === items.value.name); // 封面图
      let cover_image2:any = {}
      if(!cover_image) {
        // 无封面图获取第一张图片
        cover_image2 = currentItem.fileLists?.find((_,index:any) => index == 0);
      }
      let vertical_cover_image = currentItem.fileLists?.find((items:any) => currentItem.vertical_cover.slice(currentItem.vertical_cover.lastIndexOf('/') + 1) === items.value.name); // 竖版封面图
      let url = `https://www.huaicaikeyu.cn${currentItem.info.cover}`
      let cover_images_map = JSON.stringify([
          {
              'src': cover_image ? cover_image.value.https_url : cover_image2.value.https_url,
              'origin_src': cover_image ? url : cover_image2.value.https_url
          }
      ])
      console.log(vertical_cover_image, '竖版封面图', currentItem.info.title.length,'标题长度')
      let activityLists:any = [
        {'id': 408, 'is_checked': 1},
        {'id': 'aigc_bjh_status', 'is_checked': 1} // AI创作声明
      ]
      if(currentItem.activity_list.length > 0) {
          let activity_list = currentItem.activity_list.filter((items:any) => items.id == 'ttv');
          if(activity_list.length> 0) {
              activityLists.push({'id': 'ttv', 'is_checked': 1})  // 自动生成视频
          } else {
            activityLists.push({'id': 'ttv', 'is_checked': 0})  // 自动生成视频
          }
      }
      if(currentItem.square_mission_List.length > 0) {
          let mission_List = currentItem.square_mission_List.some((items:any) => items.id == '1600102');
          if(mission_List) {
              activityLists.push({'id': 'task_1600102', 'is_checked': 1})  // 征文任务
          } else {
              activityLists.push({'id': `task_${currentItem.square_mission_List[0].id}`, 'is_checked': 1}) // 征文任务
          }
      }
      console.log('征文任务:', activityLists)
      let objData: any = {
            'type': 'news',
            'title': currentItem.info.title.length > 30 ? currentItem.info.ai_title : currentItem.info.title,
            'content': html_content,
            'creative_method': 'bjh_pc_text',
            'vertical_cover': vertical_cover_image ? vertical_cover_image.value.https_url : '',  // 垂直图片
            'abstract': '',  // 摘要
            'len': html_content.length,
            'activity_list': activityLists,
            'source_reprinted_allow': 0,
            'abstract_from': 1,
            'isBeautify': false,
            'usingImgFilter': false,
            'cover_layout': 'one',
            'cover_images': JSON.stringify([
                {
                    'src': cover_image ? cover_image.value.https_url :  cover_image2.value.https_url,
                    'cropData': {
                        'x': 0,
                        'y': 0,
                        'width': cover_image && cover_image.value && cover_image.value.width ? cover_image.value.width : 300,
                        'height': cover_image && cover_image.value && cover_image.value.width ? cover_image.value.height :  200
                    },
                    'machine_chooseimg': 0,
                    'isLegal': 0
                }
            ]),
            '_cover_images_map': cover_images_map,
            'source': 'choose-remote',
            'cover_source': 'upload',
            'subtitle': '',
            'bjhtopic_id': '',
            'bjhtopic_info': '',
            'clue': '',
            'bjhmt': '',
            'order_id': '',
            'aigc_rebuild': '',
            'image_edit_point': JSON.stringify([
                {'img_type': "cover", 'img_num': {'template': 0, 'font': 0, 'filter': 0, 'paster': 0, 'cut': 0, 'any': 0}},
                {'img_type': "body", 'img_num': {'template': 0, 'font': 0, 'filter': 0, 'paster': 0, 'cut': 0, 'any': 0}}
            ])
        }
        const searchParams = new URLSearchParams();
        Object.keys(objData).forEach(key => {
          if (Array.isArray(objData[key])) {
            objData[key].forEach(value => {
              searchParams.append(key, value); // 对于数组，使用 append 来添加多个值
            });
          } else {
            searchParams.append(key, objData[key]); // 对于其他类型，直接添加值
          }
        });
        console.log('objData', objData, html_content)
        // executeNextOk(index + 1)
        articlePublish(objData).then((response:any) => {
            const result = response.data.ret
            console.log('result',result, currentItem.articleId)
            onuserSiteArticleSetRelease(resolve, reject, currentItem.articleId, idx + 1)
        }).catch((err) => {
          console.log(err)
          articleList.value.forEach(item1 => {
            if (currentItem.articleId == item1.article_id && item1.is_release == 0) {
              item1.isPublish = false
              item1.publishText = '发布失败'
              item1.publishReason = err.message
              item1.errorColor3 = 'error'
            }
          });
          state.loading = false;
          state.selectedRowKeys = [];
          state.selectedRows = []
          selectData.value = []
          title.value = '一键发布'
          reject(err)
        });
  }
  executeNextOk(idx)

    // 异步执行
    // selectData.value?.forEach((item: any) => {
    //   let html_content:any = '' // html内容
    //   const resultData = item.fileLists?.reduce((acc:any, item1:any) => {
    //     let matchingItem:any = ''
    //     if(!Array.isArray(item.info['images'])) {
    //       matchingItem = JSON.parse(item.info['images']).find((item2:any) => item2.url.slice(item2.url.lastIndexOf('/') + 1) === item1.value.name);
    //     } else {
    //       matchingItem = item.info['images'].find((item2:any) => item2.url.slice(item2.url.lastIndexOf('/') + 1) === item1.value.name);
    //     }
    //     if (matchingItem) {
    //       acc.push({  ...matchingItem,...item1.value }); // 将合并后的对象添加到结果数组中
    //     }
    //     return acc;
    //   }, []); // 初始值为空数组
    //   // html内容
    //   if(resultData.length > 0) {
    //     resultData.forEach((element:any, index:any) => {
    //       if(index == 0) {
    //         html_content = item.info.html_content.replace(element.key, `<img src="${element.https_url}" alt="">`);
    //       } else {
    //         html_content = html_content.replace(element.key, `<img src="${element.https_url}" alt="">`);
    //       }
    //     });
    //   } else {
    //     html_content = item.info.html_content
    //   }
    //   if(item.info['min_title'] && !Array.isArray(item.info['min_title']))  {
    //     JSON.parse(item.info['min_title']).forEach((element:any) => {
    //       html_content = html_content.replace(element.label,element.html);
    //     });
    //   }else  {
    //     item.info['min_title'].forEach((element:any) => {
    //       html_content = html_content.replace(element.label,element.html);
    //     })
    //   }
    //   const cover_image = item.fileLists?.find((items:any) => item.info.cover.slice(item.info.cover.lastIndexOf('/') + 1) === items.value.name); // 封面图
    //   let cover_images_map = JSON.stringify([
    //       {
    //           'src': cover_image ? cover_image.value.https_url : '',
    //           'origin_src': cover_image ? cover_image.value.https_url : ''
    //       }
    //   ])
    //   let objData: any = {
    //         'type': 'news',
    //         'title': item.info.title,
    //         'content': html_content,
    //         'creative_method': 'bjh_pc_text',
    //         'vertical_cover': cover_image ? cover_image.value.https_url : '',  // 垂直图片
    //         'abstract': '',  // 摘要
    //         'len': html_content.length,
    //         'activity_list': [
    //             {'id': 408, 'is_checked': 1},
    //             {'id': 'ttv', 'is_checked': 0},
    //             {'id': 'aigc_bjh_status', 'is_checked': 0}
    //         ],
    //         'source_reprinted_allow': 0,
    //         'abstract_from': 1,
    //         'isBeautify': false,
    //         'usingImgFilter': false,
    //         'cover_layout': 'one',
    //         'cover_images': JSON.stringify([
    //             {
    //                 'src': cover_image ? cover_image.value.https_url : '',
    //                 'cropData': {
    //                     'x': 0,
    //                     'y': 0,
    //                     'width': cover_image && cover_image.value && cover_image.value.width ? cover_image.value.width : 300,
    //                     'height': cover_image && cover_image.value && cover_image.value.width ? cover_image.value.height :  200
    //                 },
    //                 'machine_chooseimg': 0,
    //                 'isLegal': 0
    //             }
    //         ]),
    //         '_cover_images_map': cover_images_map,
    //         'source': 'choose-remote',
    //         'cover_source': 'upload',
    //         'subtitle': '',
    //         'bjhtopic_id': '',
    //         'bjhtopic_info': '',
    //         'clue': '',
    //         'bjhmt': '',
    //         'order_id': '',
    //         'aigc_rebuild': '',
    //         'image_edit_point': JSON.stringify([
    //             {'img_type': "cover", 'img_num': {'template': 0, 'font': 0, 'filter': 0, 'paster': 0, 'cut': 0, 'any': 0}},
    //             {'img_type': "body", 'img_num': {'template': 0, 'font': 0, 'filter': 0, 'paster': 0, 'cut': 0, 'any': 0}}
    //         ])
    //     }
    //     const searchParams = new URLSearchParams();
    //     Object.keys(objData).forEach(key => {
    //       if (Array.isArray(objData[key])) {
    //         objData[key].forEach(value => {
    //           searchParams.append(key, value); // 对于数组，使用 append 来添加多个值
    //         });
    //       } else {
    //         searchParams.append(key, objData[key]); // 对于其他类型，直接添加值
    //       }
    //     });
    //     console.log('objData', objData, html_content)
    //     articlePublish(objData).then((response:any) => {
    //         const result = response.data.ret
    //         console.log('result',result, item.articleId)
    //         onuserSiteArticleSetRelease(item.articleId)
    //         state.loading = false;
    //         state.selectedRowKeys = [];
    //         title.value = '一键发布'
    //         selectData.value = []
    //         // let arr2 = JSON.parse(sessionStorage.get('unzip-data' + current.value))
    //         // const filteredArray1 = arr2.filter((item1:any) =>
    //         //     item1.value.article_id != item.articleId
    //         // );
    //         // sessionStorage.set('unzip-data' + current.value,JSON.stringify(filteredArray1))
    //         // console.log(filteredArray1,'arr2arr2arr2')
    //     }).catch((err) => {
    //       console.log(err)
    //       state.loading = false;
    //       state.selectedRowKeys = [];
    //       title.value = '一键发布'
    //     });
    // });
};

// 设置文章已发布
const onuserSiteArticleSetRelease = async (resolve:any, reject: any,articleId:any, idx:any) => {
  await userSiteArticleSetRelease({articleId: articleId}).then((response:any) => {
    message.success(response.message);
    handleOk(resolve, reject,idx)
    // 发布后删除本地缓存文件
    let pathJson = `images_${articleId}`;
    window.electron.ipcRenderer.invoke('delete-file', pathJson+'.zip').then(res => {
      console.log(res)
      if(res.success) {
        console.log('文件删除成功')
      } else {
        console.log('删除文件失败',res.message)
      }
    })
    window.electron.ipcRenderer.invoke('delete-file', pathJson+'.json').then(res => {
      console.log(res)
      if(res.success) {
        console.log('文件删除成功')
      } else {
        console.log('删除文件失败',res.message)
      }
    })
    window.electron.ipcRenderer.invoke('delete-folder', pathJson).then(res => {
      console.log(res)
      if(res.success) {
        console.log('文件夹删除成功')
      } else {
        console.log('删除文件夹失败',res.message)
      }
    })
  }).catch(err => {
    console.log(err)
    state.loading = false;
    state.selectedRowKeys = [];
    state.selectedRows = []
    selectData.value = []
    title.value = '一键发布'
  })
}

// 文章详情
const info:any = ref({})
const onArticleDetails = (articleId:any) => {
  userSiteArticleDetails({articleId: articleId}).then((response:any) => {
        console.log(response)
        const result = response.data.data
        if(result) {
          info.value = result
          selectData.value?.forEach((item: any, index:any) => {
            if (articleId === item.articleId) {
              selectData.value[index]['info'] = result; // 替换为空的内容部分
            }
          });
        } else {
          selectData.value = selectData.value.filter((item1:any) =>articleId != item1.articleId)
          // count.value--;
          if(selectData.value.length == 0) {
            state.loading = false;
            state.selectedRowKeys = [];
            state.selectedRows = []
            selectData.value = []
            title.value = '一键发布'
            message.warning('文章为空');
          }
        }
        console.log('selectData.value',count.value, selectData.value)
        if(count.value == selectData.value.length && selectData.value.every((item2:any) => item2.modalOpen === true)) {
          count.value = 0
          Modal.confirm({
            title: '提示',
            icon: '',
            content: createVNode('div', { style: 'color:black;' }, '是否确认发布?'),
            okText: '确认',
            cancelText: '取消',
            onOk() {
              // handleOk(0)
              return new Promise((resolve, reject) => {
                const res = handleOk(resolve, reject, 0)
                console.log(res)
                return res
              }).catch(() => console.log('出错!'))
            },
            onCancel() {
              state.loading = false;
              state.selectedRowKeys = [];
              state.selectedRows = []
              selectData.value = []
              title.value = '一键发布'
            },
            class: 'test',
          });
        }
    }).catch(err => {console.log(err)})
}

// // 获取文章图片的压缩文件
// const url:any = ref([])
// const fileName:any = ref('')
function getFilenameFromURL(url) {
    // 找到最后一个 '/' 的位置
    const lastIndex = url.lastIndexOf('/');
    // 使用 substring 从最后一个 '/' 位置之后开始截取，直到字符串末尾
    const filename = url.substring(lastIndex + 1);
    // 返回文件名，但不包括后缀名
    // return filename.split('.').slice(0, -1).join('.');
    return filename;
}
// 获取压缩文件
const timer = ref()
const onArticleZipImage = () => {
  let articleLists = articleList.value.filter((item1:any) => item1.is_release == 0 && item1.status == 50 && item1.img_status == 20 && !item1.isDownload)
  articleList.value.forEach(item1 => {
    if (item1.is_release == 0 && item1.status == 50 && item1.img_status == 20 && !item1.isDownload) {
      item1.isDownload = false
      item1.downloadReason = ''
    }
  });
  console.log(articleLists, '解压数据数组')
  const executeNexts = (index) => {
    if(index >= articleLists.length) {
      console.log('没有要解压的数据了')
      timer.value =  setTimeout(() => {
        listUploadFun(0) // 上传图片
      }, 3000)
      return
    }
    const currentItem = articleLists[index];
    if(currentItem['cover'] || currentItem['vertical_cover']) {
      userSiteArticleZipImage({articleId: currentItem['article_id']}).then(async(response:any) => {
          const result = response.data
          let urlValue = {
            url: result.url,
            fileName: getFilenameFromURL(result.url),
            article_id: currentItem['article_id']
          }
          console.log(result,urlValue,'result')
          currentItem.isDownload = false
          currentItem.downloadReason = '正在下载'
          // 监听主进程的回复
          // let url = `https://www.huaicaikeyu.cn/${result.url}`
          let downloadObj:any = await download_file(result.url,currentItem['article_id'])
         console.log('下载返回的数据',downloadObj)
         let downloadResult = JSON.parse(downloadObj)
         if(downloadResult.success) {
            isDownloadResume.value = true
            if(downloadResult.status == 2 || downloadResult.status == 1) {
              console.log('解压重复数据计数');
              timer.value =  setTimeout(() => {
                listUploadFun(0) // 上传图片
              }, 2000)
              console.log(downloadResult.status,'解压成功，去上传'); 
              currentItem.isDownload = true
              currentItem.downloadReason = '已解压'
              let arr = [...isDownloadList.value,currentItem]
              isDownloadList.value = arr
            }else if(downloadResult.status == 3 || downloadResult.status == 4) {
              currentItem.isDownload = false
              currentItem.downloadReason = downloadResult.message
              timer.value =  setTimeout(() => {
                executeNexts(index)
              }, 2000)
            } else {
              timer.value =  setTimeout(() => {
                executeNexts(index + 1)
              }, 2000)
              currentItem.isDownload = false
              currentItem.downloadReason = '解压失败'
              let pathJson = `images_${currentItem['article_id']}.zip`;
              window.electron.ipcRenderer.invoke('delete-file', pathJson).then(res => {
                  if(res.success) {
                    console.log('文件删除成功')
                  } else {
                    console.log('删除文件失败',res.message)
                  }
              })
            }
            // window.electron.ipcRenderer.send('upload-file','images_119943'); // 发送文件路径到主进程
            // window.electron.ipcRenderer.on('file-uploaded', (event, blob) => {
            //   // 在这里你可以使用 Blob 或 File 进行进一步操作，例如上传到服务器或显示图片等。
            //   console.log('Received file:', blob); // 或者创建一个 URL 来显示图片等。
            // });
         } else {
            currentItem.isDownload = false
            currentItem.downloadReason = '解压失败'
            timer.value =  setTimeout(() => {
              executeNexts(index + 1)
            }, 2000)
         }
          // window.electron.ipcRenderer.invoke('download-file-request', url).then((response) => {
          //   console.log('解压返回数据',response); // 输出下载成功信息
          //   let res = JSON.parse(response)
          //   isDownloadResume.value = true
          //   if(res.status == 2 || res.status == 1) {
          //     console.log('解压重复数据计数');
          //     timer.value =  setTimeout(() => {
          //       // executeNexts(index + 1)
          //       listUploadFun(0) // 上传图片
          //     }, 2000)
          //     console.log(res.status,'解压成功，去上传'); 
          //     currentItem.isDownload = true
          //     currentItem.downloadReason = '已解压'
          //     let arr = [...isDownloadList.value,currentItem]
          //     isDownloadList.value = arr
          //   }else if(res.status == 3 || res.status == 4) {
          //     currentItem.isDownload = false
          //     currentItem.downloadReason = res.message
          //     timer.value =  setTimeout(() => {
          //       executeNexts(index)
          //     }, 2000)
          //   } else {
          //     timer.value =  setTimeout(() => {
          //       executeNexts(index + 1)
          //     }, 2000)
          //     currentItem.isDownload = false
          //     currentItem.downloadReason = '解压失败'
          //     let pathJson = `images_${currentItem['article_id']}.zip`;
          //     window.electron.ipcRenderer.invoke('delete-file', pathJson).then(res => {
          //         if(res.success) {
          //           console.log('文件删除成功')
          //         } else {
          //           console.log('删除文件失败',res.message)
          //         }
          //     })
          //   }
          //   // window.electron.ipcRenderer.send('upload-file','images_119943'); // 发送文件路径到主进程
          //   // window.electron.ipcRenderer.on('file-uploaded', (event, blob) => {
          //   //   // 在这里你可以使用 Blob 或 File 进行进一步操作，例如上传到服务器或显示图片等。
          //   //   console.log('Received file:', blob); // 或者创建一个 URL 来显示图片等。
          //   // });
          // }).catch((error) => {
          //   console.error(error); // 输出下载错误信息
          //   currentItem.isDownload = false
          //   currentItem.downloadReason = '解压失败'
          //   timer.value =  setTimeout(() => {
          //     executeNexts(index + 1)
          //   }, 2000)
          // });
      }).catch(err => {
        console.log(err);
        currentItem.isDownload = false
        currentItem.downloadReason = '下载失败'
        timer.value =  setTimeout(() => {
            executeNexts(index + 1)
          }, 2000)
      })
    } else {
      currentItem.isDownload = false
      currentItem.downloadReason = '无解压文件'
      timer.value =  setTimeout(() => {
        executeNexts(index + 1)
      }, 2000)
    }
  }
  executeNexts(0)
}

//离开界面
onBeforeUnmount(() => {
    // 每次离开当前界面时，清除定时器
    console.log('234343444444444')
    isStop.value = true
    if(timer.value) {
      clearTimeout(timer.value)
      timer.value = null
    }
    if(timer2.value) {
      clearTimeout(timer2.value)
      timer2.value = null
    }
    if(timer3.value) {
       clearTimeout(timer3.value)
      timer3.value = null
    }
})
// const images:any = ref([]); // 用于存储解压后的图片文件
const fileLists: any = ref([]); // 用于存储上传后的图片文件
const count:any = ref(0)
// 下载压缩文件并解压
// const downloadAndUnzip = async (articleId:any) => {
//   try {
//     title.value = '正在解压中...'
//     count.value++
//     // 请求 ZIP 文件
//     const response = await axios.get('https://www.huaicaikeyu.cn' + url.value, {
// 	      //请求头需要的一些配置
//         headers:{
//           token:userStore.Token,
//           'Content-Type':  'application/json; application/octet-stream' //'application/zip'
//         },
//       responseType: 'arraybuffer'
//     });

//     if(response.data) {
//         // 使用 JSZip 解压文件
//         const zip = new JSZip();
//         await zip.loadAsync(response.data);
//         // console.log('zip', zip, response)
//         // 遍历 ZIP 文件中的每个文件
//         for (const [fileName, file] of Object.entries(zip.files)) {
//           if (!file.dir) { // 如果是文件，不是文件夹
//             const fileContent = await file.async('blob'); // 获取文件内容为 Blob
//             images.value.push({ name: fileName, content: fileContent });
//             let resultstr = await handleChange({ name: fileName, content: fileContent })
//             // console.log('resultstr',resultstr)
//             selectData.value?.forEach((item: any, index:any) => {
//               if (articleId === item.articleId) {
//                 selectData.value[index]['fileLists'].push(resultstr); // 替换为空的内容部分--给数组赋值
//                 selectData.value[index]['modalOpen'] = true
//               }
//             });
//           }
//         }
//     }
//     // console.log('selectData.value',selectData.value, count.value,selectData.value.every((item2:any) => item2.modalOpen === true))
//     if(count.value == selectData.value.length && selectData.value.every((item2:any) => item2.modalOpen === true)) {
//       // setTimeout(() => {
//         state.loading = false;
//         state.selectedRowKeys = [];
//         title.value = '一键发布'
//         count.value = 0
//       // }, 1000);
//       Modal.confirm({
//         title: '提示',
//         icon: '',
//         content: createVNode('div', { style: 'color:black;' }, '是否确认发布?'),
//         okText: '确认',
//         cancelText: '取消',
//         onOk() {
//           // setTimeout(() => {
//           //      open.value = true;
//           // }, 1000)
//           handleOk()
//         },
//         onCancel() {

//         },
//         class: 'test',
//       });
//     }
//   } catch (error) {
//     console.error('下载或解压失败:', error);
//     message.error({
//       content: () => '下载或解压失败',
//       duration: 2
//     });
//     state.loading = false;
//     state.selectedRowKeys = [];
//     state.selectedRows = []
//     title.value = '一键发布'
//   }
// };

// //上传图片
// async function handleChange(image:any) {
//   //info.filename的值与a-upload里的name对应，这样就可以多个位置都使用同一方法
//   title.value = '正在上传图片中...'
//   const FormDatas = new FormData();
//   FormDatas.append("type", 'image');
//   FormDatas.append("app_id", '1788758126357619');
//   FormDatas.append("is_waterlog", '0');
//   FormDatas.append("save_material", '1');
//   FormDatas.append("is_events", '');
//   FormDatas.append("article_type", 'news');
//   FormDatas.append("media", image.content, image.name);
//   return new Promise((resolve, reject) => {
//     //api.upload_uploadImages后端给的图片上传解析的接口方法
//     pictureUploadproxy(FormDatas).then((response:any) => {
//       const result = response.ret
//       const img = new Image();
//       img.src = result.https_url;
//       img.onload = () => {
//         // 图片加载完成后，获取宽高
//         console.log('Width:', img.width, 'Height:', img.height);
//         // 可以在这里做一些处理，比如验证图片尺寸等
//       };
//       resolve(result)
//     }).catch(err => {
//       state.loading = false;
//       state.selectedRowKeys = [];
//       state.selectedRows = []
//       title.value = '一键发布'
//       reject(err)
//     })
//   });
// };
// document.cookie = "url=http://c.biancheng.net/; domain=.biancheng.net;max-age=" + 30*24*60*60;
//   document.cookie = "course=JavaScript";
//   document.cookie = "title=cookie";
// 从返回的header中解析出token
const onGetuserinfo = () => {
  // const rawString = `BAIDUID=02705B2BFEAA6355FDCD68236CDB726C:FG=1; BAIDUID_BFESS=02705B2BFEAA6355FDCD68236CDB726C:FG=1; theme=bjh; PHPSESSID=bus1880ghlh7lfufij39rvtph5; ppfuid=FOCoIC3q5fKa8fgJnwzbE67EJ49BGJeplOzf+4l4EOvDuu2RXBRv6R3A1AZMa49I27C0gDDLrJyxcIIeAeEhD8JYsoLTpBiaCXhLqvzbzmvy3SeAW17tKgNq/Xx+RgOdb8TWCFe62MVrDTY6lMf2GrfqL8c87KLF2qFER3obJGmXRS7RSHsClUBpvjWIIpNsGEimjy3MrXEpSuItnI4KD8jgu0Abw9M7DZlkeZ9TGjDZ2Rltdu1U5k+eO6Sls7CqL9Ks8gfdOYlbtrf7CzLi3xJsVwXkGdF24AsEQ3K5XBbh9EHAWDOg2T1ejpq0s2eFy9ar/j566XqWDobGoNNfmfpaEhZpob9le2b5QIEdiQez0E9SVndeXkd9EampG0PcXhLZ126CPFCIEuj/nWa+RPzg/CQV+t396RcQ+QB5B6TasmgOrJ40n63OsKSOpoSLpklEtTKfx5hHc9j4nurRrdQxO5x673r3WZWOB4sULM6VXVSGGnkUB7qA0khSm2nsQwBpdgqbXUb4lU+zNAV2n0AktybhhKxhReRo8jZOXronbjpyaNZANNqEA4g1HmtdHmv/tVUjVExnyBvjSrtrPu8IrnpcuigpPlr6uwWt/lm7TLIKKJqASWGtMQ6010Ekmrx4fAQe4UGeL1qFLCkLuVsqRTBoofr21/QMVXuElE6IsRNIWWghWQd3Lf4jYlSvUuymUDPSEyRa3+0Ti1dVRXtBxMNNlZL/aYKhL8ZXc31rBDqIzqGz8FaOWCcRrX7mFbQV3Cg0pV2IqYt/XyoW9JzPR+cLzrlLnoqS+rLXLnnkUprNdxn+PjQUm/6IsYGfeeSSAeWd7rUjwjsqG1CAideOw1L36a14YJP++P+kS+Sb5mK1x49t/bVAyV1GuW/Di4WdaYtTzhOHb0ypS5VHS/QoLlXJRRrnkhdcvkOKSMqWWQFRlkehXy2fiJffLYWrAf2pIJo//4JrEUhZWbH4V+AFGQM9PC1eNi2DOZbvibR8NTYxlrGkFlkXxi6t+hxhyYN1zEUp6ggVCZWoCgBT7dhxdC3bEpOFlnJXW/ewK+fOJ1Rm0oz1xFFR9FYG1BJvnQA8z6Cz/jTzGDsocIHwA4qlml8ik+FDREmF7DwZHRpOpiwmjUhELAzdRtuu+0nt6o8w3MlwZxJhxBabUW5sicyie973hz6nxWLbBzvYx9F54WJPMynUbqkO3Z7jSA8MZt1Aj6NtrhSNGXID70JtNZcYUpaI4ZXCZpGIlSF+pB7KTLoU96dsmC3+9Ar1MCJM; BDUSS=pjbXpwZVpMT3ltVkJDazFCNXh0LVY0QzZHWU80ZVJJbXNmNFRkMDQ5dVVmZEpuSUFBQUFBJCQAAAAAAAAAAAEAAAD33pBVTGVlenlvdW5nNjQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJTwqmeU8Kpnb3; BDUSS_BFESS=pjbXpwZVpMT3ltVkJDazFCNXh0LVY0QzZHWU80ZVJJbXNmNFRkMDQ5dVVmZEpuSUFBQUFBJCQAAAAAAAAAAAEAAAD33pBVTGVlenlvdW5nNjQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJTwqmeU8Kpnb3; RECENT_LOGIN=1; Hm_lvt_f7b8c775c6c8b6a716a75df506fb72df=1739255960; Hm_lpvt_f7b8c775c6c8b6a716a75df506fb72df=1739255960; HMACCOUNT=5907BD9732221668; __bid_n=194ef238e399296f40f746; ab_sr=1.0.1_MmU5NzI4NWM5NjM0N2JmOWNmYjMzNjBhMjI4ZjNiMjY3YWI0YWRiN2NmYzAxODgxNmQyMjFlOWMzNjYyMmE2NjNkYTI5NDAxMGVhMjllMzUwY2MzOTk3MDVhOWM3Mzg4NmQ2YzIwZjdkNTMzYTlhZmVjZWYxZjIwNDFiMmFkZjJkMTM2ZDA4YTFmZWUxM2NjYjU4ODQ0ZGZkYmEyOTVkMWE2NmE2MzE5NTEzOGZkMDJlZmExNDE5NGE5MjI4YTgyM2I5MjljNmI1MmI1YmJhOGYxZjQ5YTBkOWI0OTM0NzQ0YjBjYWExOWYzM2E0MWNhMjc2MWUwZWRiNWIyMGMyNg==; devStoken=827afae70feb291acbafd9f2448d52eb6cc33cfc6741fe4da91bc81f7c81b625; bjhStoken=97a9e9bee006b0f0447cde5539fce1c06cc33cfc6741fe4da91bc81f7c81b625; RT="z=1&dm=baidu.com&si=b0b5edc0-4a20-4b45-a081-b3495c87cf2c&ss=m6zvchq5&sl=2j&tt=26yv&bcn=https%3A%2F%2Ffclog.baidu.com%2Flog%2Fweirwood%3Ftype%3Dperf&ld=8r4xq"`;
    const rawString = route.query.cookie
    let arr = {}
    rawString.split(';').reduce((acc:any, item:any) => {
      console.log('acc',acc)
      const index = item.indexOf('='); // 找到‘=’的位置
      const [key, value] = [item.substring(0, index),item.substring(index + 1)]; //item.split('=') 先按'='拆分键和值，然后存储到对象中
      arr[key] = encodeURI(value); // 将键值对存储到对象中
    }, {});
    console.log(arr)
    for(let i in arr) {
      setCookie(i.trim(),encodeURI(arr[i]))
      // 设置默认会话的cookies
      const cookie = {
        url: 'https://baijiahao.baidu.com', // 需要设置cookie的URL
        name: i.trim(),
        value: encodeURI(arr[i]),
        path: '/',
        httpOnly: false,
        sameSite: 'no_restriction',
        domain: '.baidu.com' // 注意域名前的点表示这是一个顶级域名
      }
      // electron框架自带的去设置cookie
      window.electron.ipcRenderer.invoke('set-cookie', cookie).then(() => {
        console.log('Cookie 设置成功');
      })
      .catch(error => {
        console.error('设置 Cookie 失败:', error);
      });
    }
    getuserinfo({cookie: route.query.cookie}).then((response:any) => {
      const result:any = response.data.data
      console.log('result',result)
      storage.set(`baijiahao-Token`,response.headers.token)
      onAdnewspvtrend() // 获取阅读量
      onAdnewsincomeoverview() // 获取本月收益、本周收益
      onGetSquareMissionList() // 征文任务
      getArticlePublishNum() // 设置发布
      // document.cookie = 'test=1111;domain=;path=/;secure=true'
    //   console.log('result',result,document.cookie,window.location.hostname,document.domain)
    }).catch(err => {console.log(err)})
}
onMounted(() => {
  //
  if(!storage.get('baijiahao-Token')){
    clearCookie()
    if(route.query.cookie) {
      onGetuserinfo()
    }
    
  }
})
const siteId = ref('')
watchEffect(() => {
  if(siteId.value != route.query.siteId && storage.get('baijiahao-Token')) {
    siteId.value = route.query.siteId
    // 清空所有 Cookie
    const allCookies = Cookies.get();
    for (const cookieName in allCookies) {
      if (allCookies.hasOwnProperty(cookieName)) {
        Cookies.remove(cookieName, { path: '/' }); // 确保路径与设置时一致
      }
    }
    window.electron.ipcRenderer.invoke('clear-all-cookies').then((result) => {
      console.log(result)
    })
    setTimeout(() => {
      if(route.query.cookie) {
        onGetuserinfo()
      }
    }, 1000)
  }
})

//百家号获取阅读量
const read_amount:any = ref([])
const onAdnewspvtrend = () => {
 // 获取当前日期和时间
 const now = new Date();
  // 获取当天零点的时间戳（毫秒）
  const todayMidnight = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
  // 昨天零点的时间戳（秒）
  const yesterdayMidnight:any = (todayMidnight - 24 * 60 * 60 * 1000) / 1000; // 减去一天的时间（秒）
  // 前天零点的时间戳（秒）
  const dayBeforeYesterdayMidnight = yesterdayMidnight - 24 * 60 * 60 ; // 再减去一天的时间（秒）
  console.log("昨天的时间戳:", yesterdayMidnight,dayBeforeYesterdayMidnight);
  let obj = {
    type: 'ad_income',
    start_date: dayBeforeYesterdayMidnight,
    end_date: yesterdayMidnight,
    // start_date: 1740153600,
    // end_date: 1740240000,
    version: 3
  }
  adnewspvtrend(obj).then((response:any) => {
      const result = response.data.data
      read_amount.value  = result
  }).catch(() => {

  })
}
// 百家号获取本月收益、本周收益
const incomeInfo:any = ref({})
const onAdnewsincomeoverview = () => {
  let obj = {
    type: 'ad_news_income',
    version: 3
  }
  adnewsincomeoverview(obj).then((response:any) => {
      const result = response.data.data
      incomeInfo.value  = result
  }).catch(() => {

  })
}
// 获取征文任务列表
const mission_list:any = ref([])
const onGetSquareMissionList = () => {
  let obj = {
    page_no: 1,
    article_type: 1,
    page_size: 18,
    task_attend: 1,
    task_origin: 'market',
    task_type: -1,
    from: 'pc_edit'
  }
  getSquareMissionList(obj).then((response:any) => {
      const result = response.data.data
      mission_list.value = result.list
  }).catch(() => {
  })
}
// 百家号获取剩余发布数
const activity_list:any = ref([])
const getArticlePublishNum = () => {
  articlePublishNum({type: 'news'}).then((response:any) => {
      const result = response.data.data
      activity_list.value = result.article.activity_list
  }).catch(() => {
  })
}
// watch(() => route.query.cookie, (newValue, oldValue) => {
//   console.log(newValue, oldValue)
// })
const clearCookie = async () => {
  // 清空所有 Cookie
  const allCookies = Cookies.get();
  for (const cookieName in allCookies) {
    if (allCookies.hasOwnProperty(cookieName)) {
      Cookies.remove(cookieName, { path: '/' }); // 确保路径与设置时一致
    }
  }
  const result = await window.electron.ipcRenderer.invoke('clear-all-cookies');
  console.log(result)
}
// 获取表格选择框勾选的数据
const onSelectChange = (selectedRowKeys: Key[], selectedRows: Key[]) => {
  // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
  state.selectedRowKeys = selectedRowKeys;
  state.selectedRows = selectedRows
};
// 禁止表格某一项选中
const onGetCheckboxProps = (record: any) => ({
    disabled: record.is_release == 1, // Column configuration not to be checked
})

const current = ref<number>(1); // 页数
const pageSize = ref<number>(15); // 条数
const total = ref<number>(0); // 总数
const loading = ref<Boolean>(false) ; // 加载
// 获取文章列表
const onArticleList = () => {
    loading.value = true
  // route.query.siteId
  userSiteArticleList({page: current.value,limit: pageSize.value, siteId: route.query.siteId}).then((response:any) => {
    const result = response.data.data
    loading.value = false
    total.value = result.total
    processItems(result.data)
  }).catch(() => {
    loading.value = false
  })
}

// 默认获取是否有下载
const isDownloadList:any = ref([])
const processItems = async (data) => {
  let downloadList:any = []
    for (let i in data) {
      let path = `images_${data[i].article_id}`; // 从开始到点号位置截取字符串
      const result = await window.electron.ipcRenderer.invoke('list-directory', path); // 等待操作完成
      // console.log(result)
      // 处理结果或更新数组项
      if(Array.isArray(result.imageArr)) {
        if(result.imageArr.length != 0) {
          data[i]['isDownload'] = true
          data[i]['downloadReason'] = '已解压' // 将修改后的对象添加到新数组中
          downloadList.push(data[i])
        } else {
          data[i]['isDownload'] = false
          data[i]['downloadReason'] = ''
        }
      } else {
        data[i]['isDownload'] = false
        data[i]['downloadReason'] = ''
      }

      // 获取图片文件
      let pathJson = `images_${data[i].article_id}.json`;
      const resFile = await window.electron.ipcRenderer.invoke('json-directory', pathJson); // 等待操作完成
      // console.log(resFile,'resFile')
      if(resFile.type == 2) {
        let jsonData = JSON.parse(resFile.urlArr)
        if(jsonData.data.length == 0) {
          // 删除json文件
          window.electron.ipcRenderer.invoke('delete-file', pathJson+'.json').then(res => {
            if(res.success) {
              console.log('文件删除成功')
            } else {
              console.log('删除文件失败',res.message)
            }
          })
        } else {
          data[i]['isUpload'] = true
          data[i]['uploadText'] = '已上传'
          data[i]['uploadReason'] = '已上传' // 将修改后的对象添加到新数组中
          data[i]['imgNum'] = jsonData.data.length
          // 找到值为 3 的索引
          const index = downloadList.findIndex(item => item.article_id == data[i].article_id);
          // 如果找到，删除该索引的元素
          if (index !== -1) {
            downloadList.splice(index, 1);
          }
        }
      } else if(resFile.type == 1 && data[i]['is_release'] == 0 && data[i]['status'] == 50 && data[i]['img_status'] == 20 && data[i]['isDownload']) {
        // const resArr = await window.electron.ipcRenderer.invoke('read-file', `images_${data[i].article_id}`)
        // console.log(resArr); // 输出下载成功信息
        // if(Array.isArray(resArr)) {
        //   uploadPhotos(resArr, data[i].article_id) // 上传图片
        // }
        data[i]['isUpload'] = false
        data[i]['uploadReason'] = '' // 将修改后的对象添加到新数组中
        data[i]['uploadText'] = '' 
      } else {
        data[i]['isUpload'] = false
        data[i]['uploadReason'] = '' // 将修改后的对象添加到新数组中
        data[i]['uploadText'] = '' 
      }
    }
    isDownloadList.value = downloadList
    articleList.value = data
    onArticleZipImage()
    // listUploadFun(0) // 上传图片
};
const isDownloadResume = ref(false)
onMounted(() => {
  isStop.value = false
  onArticleList()
  //在负责渲染的vue文件created生命周期函数中接受消息，做相应处理
  window.electron.ipcRenderer.removeAllListeners('updateProgressing');
  window.electron.ipcRenderer.on('updateProgressing', (_, value) => {
      progressBar.value = value.process      
      let index3 = value.path.lastIndexOf('_')
      let filePath = value.path.substring(index3+1); // 从开始到点号位置截取字符串
      articleList.value.forEach(item1 => {
        if (filePath == item1.article_id && item1.is_release == 0 && item1.status == 50 && item1.img_status == 20 && !item1.isDownload) {
          item1.progressBar = value.process    
          if(value.type == 'completed' && value.process == '100%' && !isDownloadResume.value) {
            isDownloadResume.value = true
            item1.isDownload = true
            item1.downloadReason = '已解压'
            listUploadFun(0)
          }
        }
      });
      // console.log('进度条',articleList.value, value,progressBar.value)
  });
})
watch(() => props.activeKey, (newVal:any) => {
    if(newVal == 1) {
        isStop.value = false
        isDownloadResume.value = false
        onArticleList()
    } else {
      isStop.value = true
      clearTimeout(timer.value)
      timer.value = null
    }
})
const pageFlag = ref(false)
// 分页选项
const handleTableChange = (
  pag: { pageSize: number; current: number },
  filters: any,
  sorter: any,
) => {
  console.log(pag,filters,sorter)
  current.value = pag.current
  pageSize.value = pag.pageSize
  pageFlag.value = true
  onArticleList()
};

// 去详情页列表
const onDetails = (article_id:any) => {
  router.push({path: '/articleDetails', query: {articleId: article_id}})
}

const changeModel = (val:any) => {
  open.value = val.open_model
}


// 表单
interface FormState {
  isDownload: Number | undefined;
}
const formRef = ref();
const labelCol = { span: 10 };
const wrapperCol = { span: 14 };
const formState: UnwrapRef<FormState> = reactive({
  isDownload: undefined,
});

// const onChangeDownload = (e:any) => {
//   console.log(e)
//   onArticleZipImage()
// }

// const unzipData:any = ref([]) // 解压后文件
// 下载压缩文件并解压
// const automaticDownloadZip = () => {
//   try {
//     const promises = url.value.map((item:any) =>{
//       let imgsValue:any = {
//           article_id: '',
//           file: []
//         }
//         // 请求 ZIP 文件
//         return new Promise((resolve:any, reject:any) => {
//           setTimeout(() => {
//             axios.get('https://www.huaicaikeyu.cn' + item.value.url, {
//                 //请求头需要的一些配置
//                 headers:{
//                   token:userStore.Token,
//                   'Content-Type':  'application/zip' //'application/zip'
//                 },
//               responseType: 'blob'
//             }).then(async(response:any) => {
//               if(response.data) {
//                   imgsValue['article_id'] = item.value['article_id']
//                   //下载zip文件包本地
//                   // const url = window.URL.createObjectURL(new Blob([response.data]));
//                   // const link = document.createElement('a');
//                   // link.href = url;
//                   // eleLink.style.display = "none";
//                   // link.setAttribute('download', item.value.fileName);
//                   // document.body.appendChild(link);
//                   // link.click();
//                   // document.body.removeChild(eleLink);

//                     // 把blob格式文件转成FIle类型
//                     // let files = new window.File([response.data], item.value.fileName, {type: 'zip'})
//                     // // 读取zip压缩文件里面的文件内容
//                     // JSZip.loadAsync(files).then((zip:any) => {
//                     //   for (let key in zip.files) {
//                     //   // 用blob的格式读取，方便后面下载到本地
//                     //     let base = zip.file(zip.files[key].name).async('blob')
//                     //     base.then(res => {
//                     //       doDownload(res, zip.files[key].name)
//                     //     })
//                     //   }
//                     // })
//                   // 使用 JSZip 解压文件
//                   const zip = new JSZip();
//                   await zip.loadAsync(response.data);
//                   // console.log('zip', zip, response)
//                   // 遍历 ZIP 文件中的每个文件
//                   for (const [fileName, file] of Object.entries(zip.files)) {
//                     if (!file.dir) { // 如果是文件，不是文件夹
//                       const fileContent = await file.async('blob'); // 获取文件内容为 Blob
//                       const reader = new FileReader();
//                       reader.onload = () => {
//                         imgsValue['file'].push({ name: fileName, content: reader.result });
//                       };
//                       reader.onerror = reject;
//                       reader.readAsDataURL(fileContent);
//                     }
//                   }
//                   console.log('imgsValueimgsValueimgsValueimgsValueimgsValue',imgsValue)
//                   let array:any = [{
//                     status: "fulfilled",
//                     value: imgsValue
//                   }]
//                   unzipData.value = [...array, ...unzipData.value]
//                   let arr2 = JSON.parse(sessionStorage.get('unzip-data' + current.value))
//                   if(arr2) {
//                     sessionStorage.set('unzip-data' + current.value, JSON.stringify([...unzipData.value,...arr2]))
//                     articleList.value.forEach(item1 => {
//                       const item2 = [...unzipData.value,...arr2].find(item2 => item2.status == 'fulfilled'&&  item2.value && item2.value.article_id === item1.article_id);
//                       if (item2 && item1.is_release == 0) {
//                         if(unzipData.value) {
//                           item1.isDownload = true
//                         } else {
//                           item1.isDownload = false
//                         }
//                         item1.downloadReason = ''
//                       }
//                     });
//                   } else {
//                     if(unzipData.value.length>0) {
//                       sessionStorage.set('unzip-data' + current.value, JSON.stringify(unzipData.value))
//                       articleList.value.forEach(item1 => {
//                         const item2 = unzipData.value.find(item2 => item2.status == 'fulfilled'&&  item2.value && item2.value.article_id === item1.article_id);
//                           if (item2 && item1.is_release == 0) {
//                             if(unzipData.value) {
//                             item1.isDownload = true
//                           } else {
//                             item1.isDownload = false
//                           }
//                           item1.downloadReason = ''
//                         }
//                       });
//                     }
//                   }
//                   console.log(unzipData.value, arr2)
//                   resolve(imgsValue)
//               } else {
//                 console.log('sdfsfsdfsdfsdf')
//                 reject([])
//               }
//               // console.log(response, imgsValue)
//             }).catch((err) => {
//               console.log('errrrrrrrrrrrrrrrrrrr')
//               reject(err)
//             })
//           },1000)

//         })
//     });
//     Promise.allSettled(promises).then((response:any) => {
//       console.log(response)
//       // unzipData.value = response.filter((item1:any) => item1.status == 'fulfilled')
//       // let arr2 = JSON.parse(sessionStorage.get('unzip-data' + current.value))
//       // if(arr2) {
//       //   sessionStorage.set('unzip-data' + current.value, JSON.stringify([...unzipData.value,...arr2]))
//       //   articleList.value.forEach(item1 => {
//       //     const item2 = [...unzipData.value,...arr2].find(item2 => item2.status == 'fulfilled'&&  item2.value && item2.value.article_id === item1.article_id);
//       //     if (item2 && item1.is_release == 0) {
//       //       if(unzipData.value) {
//       //         item1.isDownload = true
//       //       } else {
//       //         item1.isDownload = false
//       //       }
//       //       item1.downloadReason = ''
//       //     }
//       //   });
//       // } else {
//       //   if(unzipData.value.length>0) {
//       //      sessionStorage.set('unzip-data' + current.value, JSON.stringify(unzipData.value))
//       //      articleList.value.forEach(item1 => {
//       //       const item2 = unzipData.value.find(item2 => item2.status == 'fulfilled'&&  item2.value && item2.value.article_id === item1.article_id);
//       //         if (item2 && item1.is_release == 0) {
//       //           if(unzipData.value) {
//       //           item1.isDownload = true
//       //         } else {
//       //           item1.isDownload = false
//       //         }
//       //         item1.downloadReason = ''
//       //       }
//       //     });
//       //   }
//       // }
//       console.log('返回：',response, JSON.parse(sessionStorage.get('unzip-data' + current.value)),unzipData.value)
//     })
//   } catch (error) {
//     console.error('下载或解压失败:', error);
//     message.error({
//       content: () => '下载或解压失败',
//       duration: 2
//     });
//   }
// }
// const doDownload = (data, name) => {
//     if (!data) {
//       return
//     }
//     let url = window.URL.createObjectURL(new Blob([data]))
//     let link = document.createElement('a')
//     link.style.display = 'none'
//     link.href = url
//     link.setAttribute('download', name)

//     document.body.appendChild(link)
//     link.click()
// }
// 示例：将 Base64 字符串转换回 Blob 对象
// function base64ToBlob(base64String) {
//   const parts = base64String.split(';base64,');
//   const contentType = parts[0].split(':')[1];
//   const raw = window.atob(parts[1]);
//   const rawLength = raw.length;
//   const uInt8Array = new Uint8Array(rawLength);

//   for (let i = 0; i < rawLength; ++i) {
//     uInt8Array[i] = raw.charCodeAt(i);
//   }

//   return new Blob([uInt8Array], { type: contentType });
// }
const downloadList = computed(() =>{
  return articleList.value.filter((item1:any, index:any) =>index< 2 && item1.is_release == 0 && item1.status == 50 && item1.img_status == 20 && item1.isDownload && !item1.isUpload)
})
console.log(downloadList.value,'llllll')
// watchEffect(() => {
//   console.log(isDownloadList.value,'watchEffect:isDownloadList.value')
//   console.log('downloadList.value',downloadList.value)
//   if(isDownloadList.value.length > 0) {
//     // listUploadFun(0) // 上传图片
//   }
// })
// const downloadList2:any = ref([])
// watch(() => articleList.value.map(item => item.is_release == 0 && item.status == 50 && item.img_status == 20 && item.isDownload && !item.isUpload), (newValues, oldValues) => {
//     console.log(newValues, oldValues)
//   newValues.forEach((flag, index) => {
//       if(flag && !oldValues[index]) {
//           console.log(index + 1,'9999999999999999')
//         downloadList2.value.push(articleList.value[index])
//       }
//   })
// },{immediate:true})
  const listUploadFun = (idx:any) => {
    let articleList2 = articleList.value.filter((item1:any) =>item1.is_release == 0 && item1.status == 50 && item1.img_status == 20 && item1.isDownload && !item1.isUpload)
    let articleList3 = articleList.value.filter((item1:any) =>item1.is_release == 1 || item1.isDownload)
    console.log(articleList2,downloadList, '可以上传图片的数据数组')
    // let articleList2 = articleList4.filter((_, index:any) =>index < 2)
    const executeNexts4 = async (index) => {
      if (index >= articleList2.length) {
        // console.log('没有上传数据了', articleList3)
        if(!isStop.value) {
          if(articleList3.length < articleList.value.length) {
            setTimeout(() => {
              if(!pageFlag.value) {
                onArticleZipImage()
              }else {
                pageFlag.value = false
              }
            }, 4000)
          }
        }
        return
      }
      const currentItem = articleList2[index];
      if(!isStop.value && currentItem.uploadReason != '正在上传') {
        const resArr = await window.electron.ipcRenderer.invoke('read-file', `images_${currentItem.article_id}`)
        // console.log(resArr); // 输出下载成功信息
        if(Array.isArray(resArr)) {
          currentItem.isUpload = false
          currentItem.uploadText = '正在上传'
          currentItem.uploadReason = '正在上传'
          uploadPhotos(resArr, currentItem.article_id, index) // 上传图片
        }
      }
    }
    executeNexts4(idx)
  }
  const imgNum = ref(0)
  // 上传图片
  const uploadPhotos = async (val:any, article_id:any, idx2:any) => {
    // title.value = '正在上传图片中...'
    // 异步请求
    // const promises = val.map((item:any) =>{
    //   const blob = new Blob([item.data],{type: "application/octet-stream"}); //, { type: `${item.type}`} 根据文件类型调整 MIME 类型
    //   // let file:any =  new File([item.data],item.name,{type:item.type})
    //   // console.log(blob, file)
    //   // if(index < 3) {
    //     const FormDatas = new FormData();
    //   FormDatas.append("type", 'image');
    //   FormDatas.append("app_id", '1788758126357619');
    //   FormDatas.append("is_waterlog", '0');
    //   FormDatas.append("save_material", '1');
    //   FormDatas.append("is_events", '');
    //   FormDatas.append("article_type", 'news');
    //   FormDatas.append("media", blob, item.name);
    //   return new Promise((resolve, reject) => {
    //     //api.upload_uploadImages后端给的图片上传解析的接口方法
    //     pictureUploadproxy(FormDatas).then((response:any) => {
    //       const result = response.data.ret
    //       let width:any = ''
    //       let height:any = ''
    //       const img = new Image();
    //       img.src = result.https_url;
    //       img.onload = () => {
    //         // 图片加载完成后，获取宽高
    //         // console.log('Width:', img.width, 'Height:', img.height);
    //         // 可以在这里做一些处理，比如验证图片尺寸等
    //         width = img.width
    //         height = img.height
    //       };
    //       let articleId = { article_id: article_id, width: width, height: height }
    //       resolve({...result, ...articleId})
    //     }).catch(err => {
    //       state.loading = false;
    //       state.selectedRowKeys = [];
    //       state.selectedRows = []
    //       title.value = '一键发布'
    //       reject(err)
    //     })
    //   });
    //   // }
    // })
    // Promise.allSettled(promises).then((res:any) => {
    //   let arr = res.filter((item1:any) => {return item1.value })
    //   selectData.value?.forEach((item: any, index:any) => {
    //     if (article_id === item.articleId) {
    //       selectData.value[index]['fileLists'] = arr; // 替换为空的内容部分--给数组赋值
    //       selectData.value[index]['modalOpen'] = true
    //       count.value++
    //     }
    //   });
    //   console.log('返回：',res,count.value, selectData.value)
    //   if(count.value == selectData.value.length && selectData.value.every((item2:any) => item2.modalOpen === true)) {
    //     count.value = 0
    //     Modal.confirm({
    //       title: '提示',
    //       icon: '',
    //       content: createVNode('div', { style: 'color:black;' }, '是否确认发布?'),
    //       okText: '确认',
    //       cancelText: '取消',
    //       onOk() {
    //         handleOk()
    //       },
    //       onCancel() {
    //         state.loading = false;
    //         state.selectedRowKeys = [];
    //         state.selectedRows = []
    //         title.value = '一键发布'
    //       },
    //       class: 'test',
    //     });
    //   }
    // })

    // 同步请求
    var array:any = []
    const executeNexts = async (index) => {
      // 判断循环执行完了后执行
      if(index >= val.length) {
        let pathJson = `images_${article_id}.json`;
        let datas = { data: array}
        console.log(datas)
        if(!isStop.value) {
          const result = await window.electron.ipcRenderer.invoke('create-file', pathJson, datas);
          console.log(result,'文件创建成功!')
          if (result.success) {
            articleList.value.forEach(item1 => {
              if (article_id == item1.article_id && item1.is_release == 0 && item1.status == 50 && item1.img_status == 20 && item1.isDownload) {
                item1.isUpload = true
                item1.uploadText = '已上传'
                item1.uploadReason = '已上传'
                item1.imgNum = imgNum.value
              }
            });
            listUploadFun(0)
          } else {
            articleList.value.forEach(item1 => {
              if (article_id == item1.article_id && item1.is_release == 0) {
                item1.isUpload = false
                item1.uploadText = '上传失败'
                item1.errorColor = 'error'
                item1.uploadReason = '文件创建失败'
              }
            });
            console.log(`创建文件失败：${result.message}`);
            // message.error({
            //   content: () => `创建文件失败: ${result.message}`,
            //   duration: 2
            // });
          }
        }
        console.log('sdsssdfsdf', array, selectData.value)
        return
      }
      if(!isStop.value) {
        const currentItem = val[index];
        const blob = new Blob([currentItem.data],{type: "application/octet-stream"}); //, { type: `${item.type}`} 根据文件类型调整 MIME 类型
        // let file:any =  new File([currentItem.data],currentItem.name,{type:currentItem.type})
        const FormDatas = new FormData();
        FormDatas.append("type", 'image');
        FormDatas.append("app_id", '1788758126357619');
        FormDatas.append("is_waterlog", '0');
        FormDatas.append("save_material", '1');
        FormDatas.append("is_events", '');
        FormDatas.append("article_type", 'news');
        FormDatas.append("media", blob, currentItem.name);
        // array = new Promise((resolve, reject) => {
          //api.upload_uploadImages后端给的图片上传解析的接口方法
          pictureUploadproxy(FormDatas).then((response:any) => {
            const result = response.data.ret
            let width:any = ''
            let height:any = ''
            const img = new Image();
            img.src = result.https_url;
            img.onload = () => {
              // 图片加载完成后，获取宽高
              // console.log('Width:', img.width, 'Height:', img.height);
              // 可以在这里做一些处理，比如验证图片尺寸等
              width = img.width
              height = img.height
            };
            let articleId = { article_id: article_id, width: width, height: height }
            imgNum.value = index + 1
            let urlValue = {
              status: 'fulfilled',
              value:{...result, ...articleId }
            }
            array.push(urlValue)
            setTimeout(() => {
              executeNexts(index + 1)
            }, 1000)
            // resolve(urlValue)
          }).catch((err) => {
            // reject(err)
            articleList.value.forEach(item1 => {
              if (article_id == item1.article_id && item1.is_release == 0) {
                item1.isUpload = false
                item1.uploadText = '上传失败'
                item1.uploadReason = err.message
                item1.errorColor = 'error'
              }
            });
            pageFlag.value = true
            setTimeout(() => {
              listUploadFun(idx2 + 1) // 失败重新返回去调用
            }, 3000)
          })
      }
    }
    executeNexts(0)
  }
const timer2 = ref()
const timer3 = ref()
const isStop = ref(false) // 是否停止
// 删除列表
const onDeleteList = () => {
  clearTimeout(timer2.value)
  timer2.value = null
    const executeNexts3 = (index) => {
      let obj = {
          currentPage: current.value,
          pageSize: pageSize.value,
          search: '',
          type: 'news',
          collection: '',
          clearBeforeFetch: false
      }
      if(!isStop.value) {
        articleLists(obj).then((response:any) => {
          const result = response.data.data
          let arr = result.list.filter((item2:any) => item2['status'] == 'rejected' || (item2['status'] == 'publish' && item2.audit_msg != '') || (item2['status'] == 'forbidden' && item2.audit_msg != ''))
          // 自动删除审核未通过的文章
          if(arr.length > 0) {
              const executeNext2 = (index) => {
                if(index >= arr.length) {
                  console.log('45645645656456546')
                  clearTimeout(timer3.value)
                  timer3.value = null
                  onDeleteList() // 调用删除列表
                  return
                }
                if(arr[index]['status'] == 'publish') {
                  // 状态已发布-先撤回再删除
                  if(!isStop.value) {
                    articleWithdraw({article_id: arr[index]['article_id']}).then((response:any) => {
                        const result = response.data
                        console.log('articleRemove',result)
                        articleRemove({article_id: arr[index]['article_id']}).then((response:any) => {
                            console.log(`异步操作: ${ arr[index]['article_id']}`, response);
                            timer3.value =  setTimeout(() => {
                              executeNext2(index+1)
                            }, 2000)
                        }).catch(() => {
                        });
                    }).catch(() => {
                    });
                  }
                } else {
                  if(!isStop.value) {
                    articleRemove({article_id: arr[index]['article_id']}).then((response:any) => {
                        console.log(`异步操作: ${ arr[index]['article_id']}`, response);
                        timer3.value =  setTimeout(() => {
                          executeNext2(index+1)
                        }, 2000)
                    }).catch(() => {

                    });
                  }
                }
                // articleRemove({article_id: arr[index]['article_id']}).then((response:any) => {
                //     console.log(`异步操作: ${ arr[index]['article_id']}`, response);
                //     timer3.value =  setTimeout(() => {
                //       executeNext2(index+1)
                //     }, 2000)
                // }).catch(() => {

                // });
              }
              executeNext2(0)
          } else {
            timer2.value =  setTimeout(() => {
              executeNexts3(index + 1)
            }, 2000)
          }
        }).catch(() => {
          loading.value = false
        })
      }
    }
    executeNexts3(0)
}
</script>
<template>
  <div class="publishList">
   <!-- <iframe id="myIframe" ref="myIframe" src='http://baijiahao.baidu.com' frameborder="0"></iframe> -->
   <a-form
    style="justify-content: end"
    ref="formRef"
    layout="inline"
    :model="formState"
    :label-col="labelCol"
    :wrapper-col="wrapperCol"
    >
      <!-- <a-form-item label="是否自动下载" name="region">
        <a-select v-model:value="formState.isDownload"  style="width: 120px" placeholder="请选择是否自动下载" @change="onChangeDownload">
          <a-select-option :value="2">是</a-select-option>
          <a-select-option :value="1">否</a-select-option>
        </a-select>
      </a-form-item> -->
      <a-form-item label="">
        <div style="margin-bottom: 16px;text-align: right;">
          <a-button type="primary" :disabled="!hasSelected" :loading="state.loading" @click="start">
            {{ title }}
          </a-button>
        </div>
      </a-form-item>
    </a-form>
    <div class="top-amount-show">
      <span class="amount">
        <span>前日阅读量：</span>({{ read_amount.length > 0 ? read_amount[0].total_pv : '0' }})
      </span>
      <span class="amount">
        <span>昨日阅读量：</span>({{ read_amount.length > 1 ? read_amount[1].total_pv : '0' }})
      </span>
      <span class="amount ">
        <span>昨日收益：</span>({{ incomeInfo.yesterday  && incomeInfo.yesterday.current ? incomeInfo.yesterday.current : '0' }})
      </span>
      <span class="amount ">
        <span>本周收益：</span>({{ incomeInfo.week && incomeInfo.week.current ? incomeInfo.week.current : '0'}})
      </span>
      <span class="amount ">
        <span>本月收益：</span>({{ incomeInfo.month  && incomeInfo.month.current ? incomeInfo.month.current : '0' }})
      </span>
    </div>
    <a-table :rowKey="(record:any) => record.article_id" :pagination="pagination" :row-selection="{ selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange, getCheckboxProps: onGetCheckboxProps }" :columns="columns" :data-source="articleList" :loading="loading" @change="handleTableChange">
        <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'title'">
              <a-tooltip :title="record.title">
                <div>
                   {{ record.title ? record.title : '' }}
                </div>
              </a-tooltip>
            </template>
            <template v-else-if="column.key === 'source_url'">
                <a :href="record.source_url" target="_blank">
                {{ record.source_url ? record.source_url : '' }}
                </a>
            </template>
            <template v-else-if="column.key === 'status'">
               <div>
                  <a-tag v-if="record.status == 10" color="success">已发布</a-tag>
                  <a-tag v-else-if="record.status == 20" color="processing">重新进入队列</a-tag>
                  <a-tag v-else-if="record.status == 30" color="error">发布失败</a-tag>
                  <a-tag v-else-if="record.status == 40" color="geekblue">AI改写中</a-tag>
                  <a-tag v-else-if="record.status == 50" color="purple">
                    <span v-if="record.img_status == 20">已改写待发布</span>
                    <span v-else>图片下载中</span>
                  </a-tag>
                  <div v-else>--</div>
               </div>
            </template>
            <template v-else-if="column.key === 'create_time'">
                <div>
                {{ record.create_time ? record.create_time : '' }}
                </div>
            </template>
            <template v-else-if="column.key === 'isDownload'">
                <div>
                   <a-tag v-if="record.isDownload" color="success">已解压</a-tag>
                   <a-tag v-else-if="!record.isDownload && record.downloadReason"  :color="record.errorColor2 ? record.errorColor2 : 'orange'">{{record.downloadReason}}{{  record.progressBar && record.downloadReason == '正在下载' ? (record.progressBar) : '' }}</a-tag>
                   <!-- {{ record.imgNum ? (record.imgNum) : '' }}  {{ imgNum ? (imgNum) : '' }}-->
                   <a-tag v-if="record.isUpload" color="blue">{{record.uploadText}}</a-tag>
                   <span v-else-if="!record.isUpload && record.uploadText">
                    <a-tooltip >
                      <template #title>
                        <span>{{record.uploadReason}}</span>
                      </template>
                      <a-tag  style="cursor: pointer;" :color="record.errorColor ? record.errorColor : 'gold'">{{record.uploadText}}</a-tag>
                    </a-tooltip>
                   </span>
                   <span v-if="!record.isPublish && record.publishReason">
                    <a-tooltip>
                      <template #title>
                        <span>{{record.publishReason}}</span>
                      </template>
                      <a-tag  style="cursor: pointer;" :color="record.errorColor3 ? record.errorColor3 : 'gold'">{{record.publishText}}</a-tag>
                    </a-tooltip>
                   </span>
                </div>
            </template>
            <template v-else-if="column.key === 'action'">
                <span>
                <a @click="onDetails(record.article_id)">详情</a>
                <!-- <a-divider type="vertical" />
                <a>Delete</a> -->
                </span>
            </template>
        </template>
    </a-table>
    <UploadPhoto :open="open" :info="info" @changeModel="changeModel"></UploadPhoto>
  </div>
</template>

<style scoped>
.top-amount-show{
  margin-bottom: 10px;
}
.green{
  color: green;
}
.red{
  color: red;
}
.amount{
  margin-right: 20px;
  font-weight: bold;
}
</style>
